package com.ask.service.businessService.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.ask.dto.LoginFormDTO;
import com.ask.dto.Result;
import com.ask.dto.UserDTO;
import com.ask.mapper.UserMapper;
import com.ask.entity.User;
import com.ask.service.businessService.IUserService;
import com.ask.threadlocals.UserHolder;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.ask.constants.RedisConstant.*;


@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 发送验证码，session存储
     *
     * @param phone
     * @param session
     * @return
     */
    @Override
    public Result sendCode2Session(String phone, HttpSession session) {
        // 1. 手机格式校验
        // 2. 生成随机数字
        String code = RandomUtil.randomNumbers(6);
        // 3. 存储至session
        session.setAttribute("code", code);
        log.info("发送验证码：{}", code);
        return Result.success(code);
    }

    /**
     * 验证码登录 by Session
     *
     * @param phone
     * @param code
     * @param session
     * @return
     */
    @Override
    public Result loginBySession(String phone, String code, HttpSession session) {
        // 1. 从session中获取code
        String codeCache = (String) session.getAttribute("code");
        if (codeCache == null || !codeCache.equals(code))
            return Result.fail("验证码错误！");
        // 2. 查询用户是否存在
        User user = query().eq("phone", phone).one();
        if (user == null)
            user = createUserByPhone(phone);
        // 3. 将用户信息存储至session
        session.setAttribute("user", BeanUtil.copyProperties(user, UserDTO.class));
        // 返回用户信息
        return Result.success(user);
    }

    /**
     * 发送验证码，redis存储
     *
     * @param phone
     * @return
     */
    @Override
    public Result sendCode2Redis(String phone) {
        // 1. 生成验证码
        String code = RandomUtil.randomNumbers(6);
        // 2. 存储验证码至redis,键为phone, 存储时常为3分钟
        redisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);
        log.info("发送验证码至redis: {}", code);
        return Result.success();
    }


    /**
     * 验证码登录 by Redis
     *
     * @param loginForm
     * @return
     */
    @Override
    public Result loginByRedis(LoginFormDTO loginForm) {
        String phone = loginForm.getPhone();
        String code = loginForm.getCode();
        // 从redis中查询验证码
        String key = LOGIN_CODE_KEY + phone;
        String codeCache = (String) redisTemplate.opsForValue().get(key);

        // 验证码校验
        if (codeCache == null || !codeCache.equals(code))
            return Result.fail("验证码错误！");

        // 根据phone查询数据库
        User user = query().eq("phone", phone).one();
        if (user == null)
            user = createUserByPhone(phone);

        // 存储用户信息至threadLocal, 方便后续请求校验
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        UserHolder.setUser(userDTO);

        // 存储用户信息至redis, 键为随机token
        String token = UUID.randomUUID().toString();
        String tokenKey = LOGIN_USER_KEY + token;

        redisTemplate.opsForValue().set(tokenKey, userDTO, LOGIN_USER_TTL, TimeUnit.MINUTES);

        log.info("登录成功，当前用户id: {}", user.getId());
        // 返回token信息
        return Result.success(token);
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    @Override
    public Result getUserInfo() {
        UserDTO user = UserHolder.getUser();
        return Result.success(user);
    }

    /**
     * 用户签到
     *
     * @return
     */
    @Override
    public Result sign() {
        // 获取用户
        Long userId = UserHolder.getUser().getId();
        // 获取日期
        LocalDateTime now = LocalDateTime.now();
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = "sign:" + userId + keySuffix;
        int dayOfMonth = now.getDayOfMonth();
        // 写入redis
        stringRedisTemplate.opsForValue().setBit(key, dayOfMonth - 1, true);
        return Result.success();
    }

    /**
     * 统计连续签到
     *
     * @return
     */
    @Override
    public Result signCount() {
        // 获取用户
        Long userId = UserHolder.getUser().getId();
        // 获取日期
        LocalDateTime now = LocalDateTime.now();
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = "sign:" + userId + keySuffix;
        int dayOfMonth = now.getDayOfMonth();

        List<Long> result = stringRedisTemplate.opsForValue().bitField(
                key,
                BitFieldSubCommands.create().
                        get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth))
                        .valueAt(0)
        );
        if (result == null || result.isEmpty())
            return Result.success(0);
        Long num = result.get(0);
        if (num == null || num == 0)
            return Result.success(0);

        int count = 0;
        while (true) {
            if ((num & 1) == 0) {
                break;

            } else {
                count++;
            }
            num >>>= 1;
        }

        return Result.success(count);
    }

    /**
     * 根据手机号创建用户
     *
     * @param phone
     * @return
     */
    private User createUserByPhone(String phone) {
        User user = User.builder().
                phone(phone)
                .nickName("user" + RandomUtil.randomString(10))
                .build();
        log.info("create user: {}", user);
        save(user);
        return user;
    }
}
